package chapter02

import cn.hutool.db.sql.Condition

/**
 * @program lu-scala01
 * @description: 函数 - 控制抽象
 * @author: zhanglu
 * @create: 2022-03-07 18:00:00
 */
object C10_FuncControlAbstration {

  def main(args: Array[String]): Unit = {
    test02
  }

  def test01() {
    //传值参数
    def f1(a: Int) = {
      println("f1_a:" + a)
    }

    f1(23)

    def f2(): Int = {
      println("f2调用")
      12
    }

    f1(f2)

    //传名参数

    //接收代码块，代码块的返回值是int类型
    def f3(a: => Int) {
      println("f3_a:" + a)
      println("f3_a:" + a)
    }

    f3(f2)
    f3(22)

    f3({
      println("这是一段代码块")
      1
    })

  }

  def test02() {
    //1.常规while循环
    var n = 2;
    while (n >= 1){
      println(n)
      n -= 1
    }
    println("********************")
    //2.用闭包实现一个函数，将代码作为参数传入，递归调用
    def luWhile(condition: => Boolean): (=> Unit) => Unit = {
      def doLoop(op: => Unit): Unit = {
        if(condition){
          op
          luWhile(condition)(op)
        }
      }
      doLoop _
    }
    n = 2
    luWhile(n >= 1){
      println(n)
      n -= 1
    }
    println("********************")
    //3.用匿名函数实现
    def luWhile2(condition: => Boolean): (=> Unit) => Unit = {
      op => {
        if(condition){
          op
          luWhile2(condition)(op)
        }
      }
    }
    n = 2
    luWhile2(n >= 1){
      println(n)
      n -= 1
    }
    println("********************")
    //4.用柯里化实现
    def luWhile3(condition: => Boolean)(op: => Unit){
      if(condition){
        op
        luWhile3(condition)(op)
      }
    }
    n = 2
    luWhile3(n >= 1){
      println(n)
      n -= 1
    }

  }


}
